package ctrl;

import model.DiningCarService;
import model.FoodService;
import model.FoodTypeService;
import model.UserService;
import util.FileUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("*.action")
//添加注解
@MultipartConfig
public class CenterController extends HttpServlet {
    public CenterController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
//        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        path = path.substring(path.lastIndexOf('/') + 1, path.indexOf(".action"));
        if (path.equals("homepage")) {
            // 首页
            FoodService food = new FoodService();
            request.setAttribute("hot", food.getHotFoods());
            request.setAttribute("special", food.getSpecialFoods());
            request.setAttribute("recomm", food.getRecommFoods());
            request.getRequestDispatcher("/pages/homepage.jsp").forward(request, response);
        } else if (path.equals("show_detail")) {
            // 菜品详细信息
            FoodService food = new FoodService();
            String id = request.getParameter("id");
            request.setAttribute("food", food.getFood(id));
            request.getRequestDispatcher("/pages/show_detail.jsp").forward(request, response);
        } else if (path.equals("login")) {
            // 用户登录
            // 读取请求参数un和pw
            String un = request.getParameter("un");
            String pw = request.getParameter("pw");
            // 判断用户名和密码是否正确
            if (un == null || pw == null || un.equals("") || pw.equals("")) {
                // 用户未登录
                request.setAttribute("msg", "请先登录！");
                request.setAttribute("href", request.getContextPath() + "/homepage.action");
                request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
            } else {
                // 调用模型进行身份验证
                UserService us = new UserService();
                Map<String, String> r = us.login(un, pw);
                System.out.println(r);
                //打印r的类型
                System.out.println(!r.isEmpty());

                if (!r.isEmpty()) {
                    // 登录成功
                    String ident = r.get("ident");
                    // 用session保存用户的登录信息
                    session.setAttribute("loginID", r.get("id"));
                    session.setAttribute("loginName", un);
                    session.setAttribute("ident", ident);

                    if (ident.equals("1")) {
                        // 管理员
                        response.sendRedirect(request.getContextPath() + "/admin/admin_list_user.action");
                        System.out.println("管理员入口");
                    } else if (ident.equals("0")) {
                        // 普通用户
                        System.out.println("普通用户入口");
                        response.sendRedirect(request.getContextPath() + "/user/user_index.action");

                    }
                } else if (r.isEmpty()) {
                    // 登录失败
                    // 不合法用户
                    request.setAttribute("msg", "用户名或密码错误！");
                    request.setAttribute("href", request.getContextPath() + "/homepage.action");
                    request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
                }
            }
        } else if (path.equals("user_index")) {
            FoodService f = new FoodService();
            String s_fn = request.getParameter("s_fn");
            String s_type = request.getParameter("s_type");
            request.setAttribute("foods", f.getFoods(s_fn, s_type));
            FoodTypeService ft = new FoodTypeService();
            request.setAttribute("types", ft.getAllTypes());
            request.getRequestDispatcher("/pages/user/user_index.jsp").forward(request, response);
        } else if (path.equals("user_add_dc")) {
            String[] ids = request.getParameterValues("ids");
            String userid = (String) session.getAttribute("loginID");
            DiningCarService dc = new DiningCarService();
            int r = dc.addToDC(userid, ids);
            request.setAttribute("msg", "成功将" + r + "个菜品加入点餐车！");
            request.setAttribute("href", request.getContextPath() + "/user/user_show_dc.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
        } else if (path.equals("user_show_dc")) {
            String userid = (String) session.getAttribute("loginID");
            DiningCarService dc = new DiningCarService();
            request.setAttribute("dc", dc.showDC(userid));
            request.getRequestDispatcher("/pages/user/user_show_dc.jsp").forward(request, response);
        } else if (path.equals("user_del_dc")) {
            String[] ids = request.getParameterValues("ids");
            DiningCarService dc = new DiningCarService();
            int r = dc.delFromDC(ids);
            request.setAttribute("msg", "成功将" + r + "个菜品从点餐车删除！");
            request.setAttribute("href", request.getContextPath() + "/user/user_show_dc.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
        } else if (path.equals("logout")) {
            session.removeAttribute("loginID");
            session.removeAttribute("loginName");
            session.removeAttribute("ident");
            session.invalidate();
            response.sendRedirect(request.getContextPath() + "/homepage.action");

        } else if (path.equals("register")) {
            request.setCharacterEncoding("utf-8");
            String un = request.getParameter("un");
            String pw = request.getParameter("pw");
            String tel = request.getParameter("tel");
            String addr = request.getParameter("addr");
            UserService us = new UserService();
            System.out.println(un);
            System.out.println(pw);
            System.out.println(tel);
            System.out.println(addr);

            if (us.check(un)) {
                //用户名可用
                int r = us.register(un, pw, tel, addr);
                System.out.println("r:" + r);
                if (r == 1) request.setAttribute("msg", "注册成功！");
                else request.setAttribute("msg", "注册失败！");
            } else {
                request.setAttribute("msg", "用户名已存在！");
            }
            request.setAttribute("href", request.getContextPath() + "/homepage.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);

        } else if (path.equals("user_edit_infos")) {
            //修改用户信息
            request.setCharacterEncoding("utf-8");
//            response.setContentType("text/html;charset=utf-8");
//            response.setCharacterEncoding("utf-8");
            String un = request.getParameter("un");

            String pw = request.getParameter("pw");
            String tel = request.getParameter("tel");
            String addr = request.getParameter("addr");
            String id = request.getParameter("id");
//            System.out.println("un" + un + "pw" + pw + "tel" + tel + "addr" + addr + "id" + id);
            Map<String, String> m = new HashMap<String, String>();
            m.put("id", id);
            m.put("username", un);
            m.put("password", pw);
            m.put("telephone", tel);
            m.put("address", addr);

            int r = new UserService().updateUser(m);
            System.out.println("r:" + r);
            if (r == 1) {
                request.setAttribute("msg", "修改成功！");
                System.out.println("修改成功");
            } else {
                request.setAttribute("msg", "修改失败！");
                System.out.println("修改失败");
            }

            request.setAttribute("href", request.getContextPath() + "/user/user_index.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
        } else if (path.equals("admin_index")) {
            request.getRequestDispatcher("/pages/admin/admin_index.jsp").forward(request, response);
        } else if (path.equals("admin_show_dc")) {
            DiningCarService dc = new DiningCarService();
            request.setAttribute("dcs", dc.showAllDC());
            request.getRequestDispatcher("/pages/admin/admin_show_dc.jsp").forward(request, response);

        } else if (path.equals("admin_list_food")) {
            String s_fn = request.getParameter("s_fn");
            String s_type = request.getParameter("s_type");
            FoodService f = new FoodService();
            request.setAttribute("foods", f.getFoods(s_fn, s_type));
            FoodTypeService ft = new FoodTypeService();
            request.setAttribute("types", ft.getAllTypes());
            request.getRequestDispatcher("/pages/admin/admin_list_food.jsp").forward(request, response);

        } else if (path.equals("admin_edit_food")) {
            String id = request.getParameter("id");
            FoodTypeService ft = new FoodTypeService();
            request.setAttribute("types", ft.getAllTypes());
            request.setAttribute("food", new FoodService().getFood(id));
            request.getRequestDispatcher("/pages/admin/admin_edit_food.jsp").forward(request, response);

        } else if (path.equals("admin_list_user")) {
            //转到用户列表页面
            request.getRequestDispatcher("/pages/admin/admin_list_user.jsp").forward(request, response);


        } else if (path.equals("admin_update_user_info")) {
            //修改用户信息
            String id = request.getParameter("id");
            String un = request.getParameter("un");
            String pw = request.getParameter("pw");
            String tel = request.getParameter("tel");
            String addr = request.getParameter("addr");
            Map<String, String> m = new HashMap<String, String>();
            m.put("id", id);
            m.put("username", un);
            m.put("password", pw);
            m.put("telephone", tel);
            m.put("address", addr);
            int r = new UserService().updateUser(m);
            if (r == 1) {
                request.setAttribute("msg", "修改成功！");
            } else {
                request.setAttribute("msg", "修改失败！");
            }
            request.setAttribute("href", request.getContextPath() + "/admin/admin_list_user.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);


        } else if (path.equals("admin_del_user")) {


            String id = request.getParameter("ID");

            UserService us = new UserService();
            int r = us.delUser(id);
            if (r == 1) {
                request.setAttribute("msg", "删除成功！");
            } else {
                request.setAttribute("msg", "删除失败！");
            }
            request.setAttribute("href", request.getContextPath() + "/admin/admin_list_user.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);

        } else if (path.equals("admin_list_foodtype")) {
            //转到食品类型列表页面
            FoodTypeService ft = new FoodTypeService();
            request.setAttribute("types", ft.getAllTypes());
            request.getRequestDispatcher("/pages/admin/admin_list_foodtype.jsp").forward(request, response);


        } else if (path.equals("admin_add_foodtype_list")) {
            //TODO:添加菜品类型
            String type = request.getParameter("typename");
            FoodTypeService foodTypeService = new FoodTypeService();
            int r = foodTypeService.addFoodType(type);
            if (r == 1) {
                request.setAttribute("msg", "添加成功！");
            } else {
                request.setAttribute("msg", "添加失败！");
            }
            request.setAttribute("href", request.getContextPath() + "/admin/admin_list_foodtype.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);


        } else if (path.equals("admin_del_one_foodtype")) {
            String id = request.getParameter("id");
            FoodTypeService foodTypeService = new FoodTypeService();
            int r = foodTypeService.deleteFoodType(id);
            if (r == 1) {
                request.setAttribute("msg", "删除成功！");
            } else {
                request.setAttribute("msg", "删除失败！");
            }
            request.setAttribute("href", request.getContextPath() + "/admin/admin_list_foodtype.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
            
        } else if (path.equals("admin_add_food")) {
            FoodTypeService ft = new FoodTypeService();
            request.setAttribute("types", ft.getAllTypes());
            request.getRequestDispatcher("/pages/admin/admin_add_food.jsp").forward(request, response);

        } else if (path.equals("admin_add_food_do")) {
            //添加菜品
            //获取参数
            try {
                //获取get 传递过来的id
                String id = request.getParameter("id");
                String foodname = request.getParameter("fn");
                String feature = request.getParameter("fea");
                String material = request.getParameter("mat");
                String type = request.getParameter("type");
                String price = request.getParameter("price");
                String comment = request.getParameter("com");
                String picture = null;
                Part img = request.getPart("img");
                System.out.println(img);
                System.out.println(img.getContentType());
                System.out.println("foodname:" + foodname);
                System.out.println("feature:" + feature);
                System.out.println("material:" + material);
                System.out.println("type:" + type);
                System.out.println("price:" + price);
                System.out.println("comment:" + comment);

//                System.out.println();
//                // 判断上传文件的扩展名是否符合要求
                String fileExtName = FileUploadUtil.getFileExtName(img);
                if (!fileExtName.equals("") && !fileExtName.equalsIgnoreCase(".jpg")
                        && !fileExtName.equalsIgnoreCase(".png") && !fileExtName.equalsIgnoreCase(".gif")) {
                    request.setAttribute("msg", "上传文件的扩展名应为jpg,png或gif！");
                    request.setAttribute("href", "javascript:history.back()");
                    request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
                } else {
                    picture = FileUploadUtil.uploadSingleFile(img, request);
                    // 调用模型插入数据库
                    FoodService f = new FoodService();
                    int r = f.addFood(foodname, feature, material, price, type, picture, comment);
                    request.setAttribute("msg", r == 1 ? "添加菜品菜品成功！" : "添加菜品失败！");
                    request.setAttribute("href", request.getContextPath() + "/admin/admin_list_food.action");
                    request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
                }
            } catch (IllegalStateException e) {
                request.setAttribute("msg", "上传文件大小应小于5M！");
                request.setAttribute("href", "javascript:history.back()");
                request.getRequestDispatcher("/pages/result.jsp").forward(request, response);

            }

        } else if (path.equals("admin_del_food")) {
            //获取要删除的菜品单个id
            String id = request.getParameter("id");
            //调用service删除菜品
            FoodService f = new FoodService();
            int r = f.deleteFood(id);
            if (r == 1) {
                request.setAttribute("msg", "删除成功！");
            } else {
                request.setAttribute("msg", "删除失败！");
            }
            request.setAttribute("href", request.getContextPath() + "/admin/admin_list_food.action");
            request.getRequestDispatcher("/pages/result.jsp").forward(request, response);


        } else if (path.equals("admin_edit_food_do")) {
            System.out.println(request.getParameter("id"));
            System.out.println(request.getParameter("fn"));

            try {
                //获取get 传递过来的id
                String id = request.getParameter("id");
                String foodname = request.getParameter("fn");
                String feature = request.getParameter("fea");
                String material = request.getParameter("mat");
                String type = request.getParameter("type");
                String price = request.getParameter("price");
                String comment = request.getParameter("com");
                String picture = null;
                Part img = request.getPart("img");
                System.out.println(img);
                System.out.println(img.getContentType());
                System.out.println("foodname:" + foodname);
                System.out.println("feature:" + feature);
                System.out.println("material:" + material);
                System.out.println("type:" + type);
                System.out.println("price:" + price);
                System.out.println("comment:" + comment);

//                System.out.println();
//                // 判断上传文件的扩展名是否符合要求
                String fileExtName = FileUploadUtil.getFileExtName(img);
                if (!fileExtName.equals("") && !fileExtName.equalsIgnoreCase(".jpg")
                        && !fileExtName.equalsIgnoreCase(".png") && !fileExtName.equalsIgnoreCase(".gif")) {
                    request.setAttribute("msg", "上传文件的扩展名应为jpg,png或gif！");
                    request.setAttribute("href", "javascript:history.back()");
                    request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
                } else {
                    picture = FileUploadUtil.uploadSingleFile(img, request);
                    // 调用模型插入数据库
                    FoodService f = new FoodService();
                    int r = f.editFood(foodname, feature, material, price, type, picture, comment, id);
                    request.setAttribute("msg", r == 1 ? "修改菜品成功！" : "修改菜品失败！");
                    request.setAttribute("href", request.getContextPath() + "/admin/admin_list_food.action");
                    request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
                }
            } catch (IllegalStateException e) {
                request.setAttribute("msg", "上传文件大小应小于5M！");
                request.setAttribute("href", "javascript:history.back()");
                request.getRequestDispatcher("/pages/result.jsp").forward(request, response);

            }

        }

    }
}

